﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ServiceProcess;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using GmaWebservice.Configurator.Data;
using GmaWebService.Code.Helper;
using System.IO;
using GmaWebService.Interfaces;

namespace GmaWebservice.Configurator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ServiceController mGmaServiceController;
        private DispatcherTimer mGmaServiceWatcher;
        private ObservableCollection<StreamingSession> mStreamingSessions = new ObservableCollection<StreamingSession>();
        private GmaService.MediaAccessServiceClient mServiceClient;

        public ObservableCollection<StreamingSession> StreamingSessions
        { get { return mStreamingSessions; } }

        public MainWindow()
        {
            InitializeComponent();
            mGmaServiceController = new ServiceController("GmaWebService");

            mGmaServiceWatcher = new DispatcherTimer();
            mGmaServiceWatcher.Interval = TimeSpan.FromSeconds(2);
            mGmaServiceWatcher.Tick += timer1_Tick;
            mGmaServiceWatcher.Start();

            mStreamingSessions.Add(new StreamingSession
            {
                Client = "Test",
                File = "C:\\test.avi",
                Profile = "Android",
                Progress = 10
            });

            InitWebservice();
        }

        private void InitWebservice()
        {
            String user = null;
            String pass = null;
            Utils.GetLogin(out user, out pass, true);

            mServiceClient = new GmaService.MediaAccessServiceClient("BasicHttpBinding_IMediaAccessService", Properties.Settings.Default.ServiceConnection);
            mServiceClient.ClientCredentials.UserName.UserName = user;
            mServiceClient.ClientCredentials.UserName.Password = pass;
        }



        private void timer1_Tick(object sender, EventArgs e)
        {
            mGmaServiceController.Refresh();
            HandleServiceState(mGmaServiceController.Status);
            //timer.Stop();

            //this.Close();

        }

        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (TabDatabases.IsSelected)
            {
                DBLocations dbLocations = Utils.GetMPDbLocations();
                txtDbLocationMopi.Text = dbLocations.MovingPictures;
                txtDbLocationMopi.CaretIndex = txtDbLocationMopi.Text.Length;

                txtDbLocationMusic.Text = dbLocations.Music;
                txtDbLocationMusic.CaretIndex = txtDbLocationMusic.Text.Length;

                txtDbLocationVideos.Text = dbLocations.Videos;
                txtDbLocationVideos.CaretIndex = txtDbLocationVideos.Text.Length;

                txtDbLocationTvSeries.Text = dbLocations.TvSeries;
                txtDbLocationTvSeries.CaretIndex = txtDbLocationTvSeries.Text.Length;

                txtDbLocationPictures.Text = dbLocations.Pictures;
                txtDbLocationPictures.CaretIndex = txtDbLocationPictures.Text.Length;
            }

        }

        private void HandleServiceState(ServiceControllerStatus _status)
        {
            switch (_status)
            {
                case ServiceControllerStatus.Stopped:
                    btnStartStopService.Content = "Start";
                    lblServiceState.Content = "Service Stopped";
                    break;
                case ServiceControllerStatus.Running:
                    btnStartStopService.Content = "Stop";
                    lblServiceState.Content = "Service Started";
                    break;
                case ServiceControllerStatus.StartPending:
                    btnStartStopService.Content = "Stop";
                    lblServiceState.Content = "Service Starting";
                    break;
                default:
                    lblServiceState.Content = "Service " + _status.ToString();
                    break;

            }
        }

        private void btnStartStopService_Click(object sender, RoutedEventArgs e)
        {
            if (mGmaServiceController.Status == ServiceControllerStatus.Stopped)
            {
                mGmaServiceController.Start();
            }
            else if (mGmaServiceController.Status == ServiceControllerStatus.Running)
            {
                mGmaServiceController.Stop();
            }
        }

        private void btnBrowseVideos_Click(object sender, RoutedEventArgs e)
        {
            BrowseForDbLocation(DatabaseType.Videos);
        }

        private void btnBrowseMopi_Click(object sender, RoutedEventArgs e)
        {
            BrowseForDbLocation(DatabaseType.Mopi);
        }

        private void btnBrowseTvSeries_Click(object sender, RoutedEventArgs e)
        {
            BrowseForDbLocation(DatabaseType.TvSeries);
        }

        private void btnBrowseMusic_Click(object sender, RoutedEventArgs e)
        {
            BrowseForDbLocation(DatabaseType.Music);
        }

        private void btnBrowsePictures_Click(object sender, RoutedEventArgs e)
        {
            BrowseForDbLocation(DatabaseType.Pictures);
        }

        private void btnTestVideos_Click(object sender, RoutedEventArgs e)
        {
            int count = mServiceClient.GetVideosCount();
            WebMovie[] items = mServiceClient.GetVideos(0, 1, GmaWebService.Interfaces.SortBy.Name, GmaWebService.Interfaces.OrderBy.Asc);
            if (items != null)
            {
                MessageBox.Show(count + " Videos in Database", "Success");
            }
            else
            {
                MessageBox.Show("Couldn't open database", "Error");
            }
        }

        private void btnTestMopi_Click(object sender, RoutedEventArgs e)
        {
            int count = mServiceClient.GetMovieCount();
            WebMovie[] items = mServiceClient.GetMovies(0, 1, GmaWebService.Interfaces.SortBy.Name, GmaWebService.Interfaces.OrderBy.Asc);
            if (items != null)
            {
                MessageBox.Show(count + " Movies in Database", "Success");
            }
            else
            {
                MessageBox.Show("Couldn't open database", "Error");
            }
        }

        private void btnTestTvSeries_Click(object sender, RoutedEventArgs e)
        {
            int count = mServiceClient.GetSeriesCount();
            WebSeries[] items = mServiceClient.GetSeries(0, 1, GmaWebService.Interfaces.SortBy.Name, GmaWebService.Interfaces.OrderBy.Asc);
            if (items != null)
            {
                MessageBox.Show(count + " Tv Shows in Database", "Success");
            }
            else
            {
                MessageBox.Show("Couldn't open database", "Error");
            }
        }

        private void btnTestMusic_Click(object sender, RoutedEventArgs e)
        {
            int count = mServiceClient.GetAlbumsCount();
            WebMusicAlbum[] items = mServiceClient.GetAlbums(0, 1, GmaWebService.Interfaces.SortBy.Name, GmaWebService.Interfaces.OrderBy.Asc);
            if (items != null)
            {
                MessageBox.Show(count + " Albums in Database", "Success");
            }
            else
            {
                MessageBox.Show("Couldn't open database", "Error");
            }
        }

        private void btnTestPictures_Click(object sender, RoutedEventArgs e)
        {
                MessageBox.Show("Not implemented yet", "Error");
        }

        private enum DatabaseType { Pictures, Videos, Music, Mopi, TvSeries }

        private void BrowseForDbLocation(DatabaseType _db)
        {
            // Open document
            string oldFolder = null;

            switch (_db)
            {
                case DatabaseType.Pictures:
                    oldFolder = Utils.GetMPDbLocations().Pictures;
                    break;
                case DatabaseType.Videos:
                    oldFolder = Utils.GetMPDbLocations().Videos;
                    break;
                case DatabaseType.Music:
                    oldFolder = Utils.GetMPDbLocations().Music;
                    break;
                case DatabaseType.Mopi:
                    oldFolder = Utils.GetMPDbLocations().MovingPictures;
                    break;
                case DatabaseType.TvSeries:
                    oldFolder = Utils.GetMPDbLocations().TvSeries;
                    break;
            }

            // Configure open file dialog box
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            if (oldFolder != null)
            {
                dlg.InitialDirectory = new FileInfo(oldFolder).Directory.FullName;
            }

            dlg.DefaultExt = ".db"; // Default file extension
            dlg.Filter = "Database files (.db3)|*.db3|All files (.*)|*.*"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;

                switch (_db)
                {
                    case DatabaseType.Pictures:
                        txtDbLocationPictures.Text = filename;
                        Utils.ChangeDbLocation("pictures", filename);
                        break;
                    case DatabaseType.Videos:
                        txtDbLocationVideos.Text = filename;
                        Utils.ChangeDbLocation("videos", filename);
                        break;
                    case DatabaseType.Music:
                        txtDbLocationMusic.Text = filename;
                        Utils.ChangeDbLocation("music", filename);
                        break;
                    case DatabaseType.Mopi:
                        txtDbLocationMopi.Text = filename;
                        Utils.ChangeDbLocation("movingpictures", filename);
                        break;
                    case DatabaseType.TvSeries:
                        txtDbLocationTvSeries.Text = filename;
                        Utils.ChangeDbLocation("tvseries", filename);
                        break;
                }
            }


        }

        private void cmdTestWebservice_Click(object sender, RoutedEventArgs e)
        {
            WebServiceDescription functions = mServiceClient.GetServiceDescription();

            if (functions != null)
            {
                String functionString = "Functions:";
                functionString += "\nSupports Videos: " + functions.SupportsVideos.ToString();
                functionString += "\nSupports Movies: " + functions.SupportsMovingPictures.ToString();
                functionString += "\nSupports Series: " + functions.SupportsTvSeries.ToString();
                functionString += "\nSupports Music: " + functions.SupportsMusic.ToString();
                functionString += "\nSupports Pictures: " + functions.SupportsPictures.ToString();


                MessageBox.Show(functionString, "Service connected!");
            }
            else
            {
                MessageBox.Show("No connection to service");
            }
        }

        private void cmdUpdateConfig_Click(object sender, RoutedEventArgs e)
        {
            if (Utils.SetLogin(txtUsername.Text, txtUserPassword.Text))
            {
                MessageBox.Show("Successfully updated config");
            }
            else
            {
                MessageBox.Show("Error updating config");
            }

            InitWebservice();
        }
    }

}
